package com.fanli.scheduler.utils;



import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.UnknownHostException;


/**
 * Created by wei.shen on 2016/4/5.
 */
public class ElasticSearchManager {

    private static final Logger LOG = LoggerFactory.getLogger(ElasticSearchManager.class);
    private static final String clusterName = "fanli-bigdataes";
    private static final String transportHost = "192.168.3.206";

    private static ElasticSearchManager manager;
    private static Client client;

    private ElasticSearchManager(){}


    public static ElasticSearchManager instance() {
        if (manager == null) {
            manager = new ElasticSearchManager();
        }
        return manager;
    }

    public static Client getEsClient() {
        if (client == null) {
            return instance().buildClient();
        }
        else return client;
    }

    private Client buildClient() {
        Settings settings = Settings.settingsBuilder().put("cluster.name", clusterName).build();
        TransportClient client = null;
        try {
            client = TransportClient.builder().settings(settings).build()
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(transportHost), 9300));
            LOG.info("ElasticSearch client is running at :" + transportHost + ":9300");
        } catch (UnknownHostException e) {
            throw new RuntimeException("Elasticsearch host is unknown:" + transportHost);
        }

        return client;
    }
}
